#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <cstdlib> //stdlib.h
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define N 2
#define NUM 1024

using namespace std;

void Write(int wfd)
{
    sleep(1);

    string s = "hello, I am child";
    pid_t id = getpid();
    char buffer[NUM];
    int number = 0;
    while (true)
    {
        buffer[0] = 0; // 字符串清空，只是为了告诉读代码的人这是字符串
        snprintf(buffer, sizeof(buffer), "%s-%d-%d\n", s.c_str(), id, number++); // 向缓冲区写，会自动往最后添加终止符
        write(wfd, buffer, strlen(buffer)); // 向管道写
        if (number == 5)
            break;
    }
}

void Reader(int rfd)
{
    char buffer[NUM];
    while (true)
    {
        buffer[0] = 0;
        ssize_t n = read(rfd, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            cout << "father get a message[" << getpid() << "]#" << buffer << endl;
        }
        else if (n == 0)
        {
            cout << "father get a message fail" << endl;
            break;
        }
        else 
            break;
    }
}

int main()
{
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    if (n < 0)
        return 1;
    
    pid_t id = fork();
    if (id < 0)
        return 2;
    if (id == 0) //子进程
    {
        //关闭读fd
        close(pipefd[0]);

        Write(pipefd[1]);

        close(pipefd[1]); // 不写也会自动关
        exit(0);
    }
    // 父进程
    close(pipefd[1]);

    Reader(pipefd[0]);

    pid_t rid = waitpid(id, nullptr, 0);
    if (rid < 0)
        return 3;

    close(pipefd[0]);
    return 0;
}